import {getOrderList, orderCancel, orderPay} from "../../api/order";
import Util from "../../utils/util";
import Status from "../../utils/status";

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false, // 是否加载中
    loadend: false, // 是否加载完毕
    loadTitle: '加载更多内容', // 提示语
    page: 1,
    lists: [],
    et_show: true,

    statusType: [
      "全部订单",
      "待付款",
      "已接单",
      "配送中",
      "售后/退款"
    ],

    statusList: {
      1: "待付款",
      10: "进行中",
      11: "待接单",
      12: "出餐中",
      20: "已完成",

      21: "取餐中",
      22: "待配送",
      23: "配送中",
      24: "已送达",

      60: "已退款",
      80: "已取消",
    },

    cancelDialog: false,
    reasonIndex: '',
    selectIndex: 0,
    tabIndex: 0,
    btnActive: true,

    reasonList: [], //退单理由
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;
    wx.showLoading({
      title: "正在加载..."
    })
    Util.chekWxLogin().then(res => {

      that.setData({
        userInfo: res.userInfo,
        loadend: false,
        page: 1,
        isShowHistory: false,
        reasonList: Status.reasonList(),
        lists: []
      })

      that.getLists()
      wx.hideLoading()

    }).catch(errmsg => {
      wx.hideLoading()
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const status = app.globalData.orderStatus;
    if (!Util.isEmpty(status)) {
      this.setData({
        tabIndex: status,
        loadend: false,
        loading: false,
        page: 1,
        lists: [],
      })
      this.getLists();
    }
  },

  getLists() {
    const that = this
    let lists = that.data.lists || []

    if (that.data.loadend || that.data.loading) {
      return;
    }

    that.setData({loading: true, loadTitle: '加载更多内容'});
    let filter = that.data.filter || {}
    if (app.globalData.orderStatus) {
      filter['status'] = app.globalData.orderStatus
    } else {
      filter['status'] = this.data.tabIndex
    }

    filter['page_num'] = that.data.page;
    getOrderList(filter).then(res => {
      const list = res.data.items || []
      const loadend = res.data.last_page <= that.data.page;
      lists = Util.SplitArray(list, lists);
      that.setData({
        lists: lists,
        loadend: loadend,
        loading: false,
        loadTitle: loadend ? '已全部加载' : '正在加载...',
        total: res.data.total,
        page: that.data.page + 1,
        et_show: lists.length > 0,
      });

      lists.map(order => ({...order, countdown: ''}))

      that.countdown();
      wx.stopPullDownRefresh()
    }).catch(errmsg => {
      wx.stopPullDownRefresh()
      Util.Tips({title: errmsg, hideMask: true});
    })
  },

  countdown: function () {
    const now = new Date();
    if (Util.isEmpty(this.data.lists)) return;
    this.data.lists.map(order => {
      if (order.status != 1) return;

      const deadline = new Date(order.end_time);
      const timeLeft = deadline - now; // 计算剩余时间
      if (timeLeft > 0) {
        const days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
        const hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);

        order.countdown = `${minutes}分${seconds}秒`;
      } else {
        order.countdown = '已截止';
        order.status = order.current_status = 80;
        orderCancel(order.out_trade_no, '', 'countdown');//取消
      }

    });

    this.setData({lists: this.data.lists}); // 更新页面数据
    // 设置下一次倒计时
    setTimeout(this.countdown.bind(this), 1000);
  },

  confirmCancelTip(e) {
    const that = this,
      selectIndex = this.data.selectIndex;

    let lists = this.data.lists || []
    if (this.data.reasonIndex.length === 0) {
      return Util.Tips({title: "请选择取消原因", hideMask: true});
    }
    if (!this.data.btnActive)
      return false;

    this.setData({
      btnActive: false
    })
    wx.showLoading({title: "正在取消..."})
    orderCancel(lists[selectIndex].out_trade_no, this.data.reasonList[this.data.reasonIndex]).then(res => {
      lists[selectIndex].status = lists[selectIndex].current_status = lists[selectIndex].status === 1 ? 80 : 60
      that.setData({
        lists: lists,
        selectIndex: "",
        cancelDialog: false,
        btnActive: true
      })
      Util.Tips({title: res.msg || "取消成功", hideMask: true})
    }).catch(errmsg => {
      that.setData({
        btnActive: true
      })
      Util.Tips({title: errmsg})
    })

  },

  goPay(e) { //去支付
    const that = this,
      index = e.currentTarget.dataset.index;
    let lists = this.data.lists || []

    if (!this.data.btnActive)
      return false;

    this.setData({
      btnActive: false
    })

    wx.showLoading({title: "正在支付..."})
    orderPay({order_id: lists[index].out_trade_no})
      .then(res => {
        let data = res.data
        if (!Util.isEmpty(data.status) && data.status === 10) {
          lists[index].status = lists[index].current_status = 11;

          that.setData({
            lists: lists,
            btnActive: true
          })
          return;
        }

        wx.requestPayment({
          'timeStamp': data.timeStamp,
          'nonceStr': data.nonceStr,
          'package': data.package,
          'signType': 'MD5',
          'paySign': data.paySign,
          success: function (res) {
            lists[index].status = lists[index].current_status = 11;
            that.setData({
              lists: lists,
              btnActive: true
            })

            return Util.Tips({
              title: "付款成功",
              icon: "success",
              hideMask: true
            })
          },
          fail: function (res) {
            that.setData({
              btnActive: true
            })
            return Util.Tips({
              title: "取消支付成功",
              hideMask: true
            })
          }
        })
      }).catch(errmsg => {
      Util.Tips({title: errmsg, hideMask: true})
    }).finally(() => {
      that.setData({
        btnActive: true
      })

    });
  },

  showDialog(e) {
    this.setData({
      cancelDialog: true,
      selectIndex: e.currentTarget.dataset.index
    })
  },

  closeCancelDialog(e) {
    this.setData({
      cancelDialog: false
    })
  },

  radioChange(e) {
    this.setData({
      reasonIndex: e.detail.value
    })
  },

  changeNav(e) {
    app.globalData.orderStatus = ""
    this.setData({
      loadend: false,
      loading: false,
      page: 1,
      lists: [],
      tabIndex: e.currentTarget.dataset.index
    })

    this.getLists()
  },

  makePhoneCall(e) {
    const mobile = e.currentTarget.dataset.mobile;
    Util.callPhone(mobile)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

    this.setData({
      loadend: false,
      loading: false,
      page: 1,
      lists: []
    });

    this.getLists();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.getLists();
  },

  onLoadTabbar: function (e) {//底部tabbar返回数据
    this.setData({
      bottom: parseInt(e.detail)
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})